import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { setSearchParams, setBillingTab } from 'actions/billing'
import { Button, message, Col, Row, Card, Checkbox, Icon, Menu, Modal, Spin, Dropdown, Pagination } from 'antd';
import menuRoute from 'routes/menuRoute'
import SlideFrame from 'components/slide-frame'
import NewBillingForm from 'containers/financial-management/wait-for-billing/new-billing/new-billing-form'
import OpenTicketFrame from 'containers/financial-management/wait-for-billing/new-billing/open-ticket-frame'
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import 'styles/setting/wait-for-billing/new-billing.scss'
import moment from "moment/moment";

class NewBilling extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading:false,
      receiptRules:[],
      keyInvoiceOIDArray:[],
      openReceips:[],
      frameData:{},
      billingType: props.billingType,
      showSlideFrame:false,
      page: 0,
      total: 0,
      modelEnum: 'CURRENT_PAGE',
      excludeOids: [],
      title: 'CURRENT_PAGE',
      checked: false,
      openLoading: false
    };
    this.newBillingRouter = menuRoute.getRouteItem('new-billing-rule');
    this.editBillingRouter = menuRoute.getRouteItem('edit-billing-rule');
    this.searchNewBilling = menuRoute.getRouteItem('search-new-billing');
  }

  componentDidMount(){
    this.getAllRules();
  }

  getAllRules = () => {
    this.setState({loading: true});
    let { billingType, page, modelEnum, keyInvoiceOIDArray, excludeOids } = this.state;
    BillingService.getAllReceiptRules(billingType,page).then(res => {
      if(modelEnum === 'ALL_PAGE'){
        res.data.rows.map(item => {
          excludeOids.indexOf(item.keyInvoiceOID) === -1 && keyInvoiceOIDArray.addIfNotExist(item.keyInvoiceOID);
        })
      }
      this.setState({
        receiptRules: res.data.rows,
        total: res.data.total,
        loading: false,
        keyInvoiceOIDArray
      });
    }).catch(err => {
      this.setState({
        loading: false
      });
    });
  };

  renderList = (items,obj,showValue) =>{
    if(items[obj] && items[obj].length >0){
      return (
        items[obj].map((item,index) => <span className='column-content'>{item[showValue]}{index!=items[obj].length-1?'、':""}</span>)
      )
    } else {
      return (
        <Col span={18}><span className='column-content'>{messages('financial-management.key432'/*全部*/)}</span></Col>
      )
    }
  };


  //渲染收件信息
  renderAddressDetail = (item)=>{
    let info;
    let email = ['ELECTRONICORDINARY'];
    if (~email.indexOf(item.invoiceTypeResp.type)) {
      info = item.email;
    } else {
      info=item.receiverDTO?`${item.receiverDTO.receiverAddress}、${item.receiverDTO.receiverName}、${item.receiverDTO.receiverPhone}、${item.receiverDTO.receiverZipCode}`:''
    }
    return (
        <span className='column-content'>{info}</span>
    )
  };

  //打开批量开票slideFrame
  showTicketModal = () => {
    const { keyInvoiceOIDArray, billingType, modelEnum, excludeOids } = this.state;
    const { tenant } = this.props;
    let params = {
      modelEnum,
      tenantId: tenant.id,
      vendor: billingType
    };
    modelEnum === 'CURRENT_PAGE' ? (params.currentPageOids = keyInvoiceOIDArray) : (params.excludeOids = excludeOids);
    BillingService.getBatchOpenTicketInfo(params).then(res => {
      this.setState({
        frameData: {
          openReceips: res.data.rows,
          type: 'batch'
        },
        showSlideFrame: true
      })
    }).catch(e => {
      message.error(e.response.data.message);
    });
  };

  openTicket = () => {
    const { keyInvoiceOIDArray, billingType, modelEnum, excludeOids } = this.state;
    const { tenant } = this.props;
    let params = {
      modelEnum,
      tenantId: tenant.id,
      vendor: billingType
    };
    modelEnum === 'CURRENT_PAGE' ? (params.currentPageOids = keyInvoiceOIDArray) : (params.excludeOids = excludeOids);
    this.setState({ openLoading: true });
    BillingService.openTicket(params).then(() => {
      this.setState({ keyInvoiceOIDArray: [], excludeOids: [], checked: false, openLoading: false, modelEnum: 'CURRENT_PAGE' }, () => {
        message.success(messages('financial-management.key443')/*开票成功*/);
      })
    }).catch(e => {
      this.setState({ openLoading: false });
      message.error(e.response.data.message);
    });
  };

  showSlide = (flag) =>{
    this.setState({showSlideFrame:flag})
  };

  //查询开票
  toSearchNewBilling = (value) => {
    let searchParams = this.handleValue(value);
    this.props.dispatch(setSearchParams(searchParams));
    this.props.dispatch(setBillingTab('wait'));
    this.context.router.push({
      pathname: `${this.searchNewBilling.url.replace(':billingType', this.state.billingType)}`,
      state: {params: searchParams}
    });
  };

  handleValue = value => {
    let searchParams = {};
    let { billingType } = this.state;
    searchParams.vendorAccountId = value.vendorAccountId ? value.vendorAccountId : (value.company ? value.company.vendorAccountId : null);
    searchParams.tenantId = this.props.tenant.id;
    searchParams.vendor = billingType;
    searchParams.company = value.company;
    searchParams.expenseSearchLegalEntityOIDs = value.expenseLegalEntity === undefined ? [] :value.expenseLegalEntity.map(item => {return item.companyReceiptedOID});
    searchParams.expenseSearchDepartmentOIDs = value.expenseDepartment === undefined ? [] :value.expenseDepartment.map(item => {return item.value});
    searchParams.costCenterOIDs = value.costCenter === undefined ? [] :value.costCenter.map(item => {return item.costCenterItemOID});
    if(value.dateRadio === 'thisMonth'){
      searchParams.selectMode = value.dateRadio
    }
    value.commercialType && value.commercialType.commercialTypeKey && (searchParams.bankCardType = value.commercialType.commercialTypeKey);
    value.startDate && (searchParams.startDate = moment(value.startDate).format('YYYY-MM-01 00:00:00'));
    value.endDate && (searchParams.endDate = moment(value.endDate).format('YYYY-MM-DD 23:59:59'));
    searchParams.recDateTypeEnum = value.recDateTypeEnum;
    return searchParams;
  };

  //新建开票规则
  newBillingRule = values => {
    this.props.dispatch(setSearchParams(values));
    this.props.dispatch(setBillingTab('wait'));
    this.context.router.push({
      pathname: `${this.newBillingRouter.url.replace(':billingType', this.state.billingType)}`,
      state: {params: values}
    });
  };

  //开票条件checkbox变化
  boxChange = (e) => {
    let { keyInvoiceOIDArray, modelEnum, excludeOids } = this.state;
    if (e.target.checked) {
      modelEnum === 'ALL_PAGE' && excludeOids.splice(excludeOids.findIndex(o => o === (e.target.value || e.currentTarget.value)), 1);
      keyInvoiceOIDArray.addIfNotExist(e.target.value || e.currentTarget.value)
    } else {
      modelEnum === 'ALL_PAGE' && excludeOids.addIfNotExist(e.target.value || e.currentTarget.value);
      keyInvoiceOIDArray.splice(keyInvoiceOIDArray.findIndex(o => o === (e.target.value || e.currentTarget.value)), 1)
    }
    this.setState({ keyInvoiceOIDArray, excludeOids })
  };

  //全选按钮
  chooseAllRules = (e) => {
    let { receiptRules, keyInvoiceOIDArray, title } = this.state;
    if (e.target.checked) {
      receiptRules.map(item => {
        keyInvoiceOIDArray.addIfNotExist(item.keyInvoiceOID)
      });
      this.setState({ keyInvoiceOIDArray, excludeOids: [], modelEnum: title, checked: true });
    } else {
      this.setState({ keyInvoiceOIDArray: [], excludeOids: [], modelEnum: 'CURRENT_PAGE', checked: false })
    }
  };

  handleChangeType = e => {
    this.setState({ title: e.key },() => {
      this.chooseAllRules({ target : { checked: false } });
    });
  };

  //侧拉关闭
  handleCloseSlide = (success)=>{
    if(success){
      this.setState({ keyInvoiceOIDArray: [], excludeOids: [], checked: false, modelEnum: 'CURRENT_PAGE' })
    }
    this.setState({ showSlideFrame : false})
  };

  //删除开票条件
  confirmDeleteRule = (id)=>{

    Modal.confirm({
      title: messages('financial-management.key496'/*确认删除*/),
      content: messages('financial-management.key497'/*确认要删除该条规则吗?*/),
      okText: messages('financial-management.key478'/*确定*/),
      cancelText: messages('financial-management.key401'/*取消*/),
      onOk: ()=>{
        BillingService.deleteTicketRules(id).then(res =>{
          if(res.status === 200){
            message.success(messages('financial-management.key498'/*删除成功*/))
            this.getAllRules()
          }
        })
      }
    });
  };

  //单个开票
  singleOpenTicket(id) {
    let { billingType } = this.state;
    const { tenant } = this.props;
    let params = {
      currentPageOids: [id],
      modelEnum: 'CURRENT_PAGE',
      tenantId: tenant.id,
      vendor: billingType
    };
    this.setState({ keyInvoiceOIDArray: [] }, () => {
      BillingService.getBatchOpenTicketInfo(params).then(res => {
        this.setState({
          frameData: {
            openReceips: res.data.rows,
            type: 'single'
          },
          showSlideFrame: true
        })
      }).catch(e => {
        message.error(e.response.data.message);
      })
    })
  };

  //开票条件操作列表
  menuHandleClick = (e,value)=>{
    switch (e.key){
      case 'delete':{
        this.confirmDeleteRule(value);
        break;
      }
      case 'open':{
        this.singleOpenTicket(value);
        break;
      }
      case 'edit':{
        this.props.dispatch(setBillingTab('wait'));
        this.context.router.push(this.editBillingRouter.url.replace(':id',value).replace(':billingType',this.state.billingType))
      }
    }
  };

  //渲染开票周期
  renderTicketPeriod = (item)=>{

    if(item.receiptedPeriodState === 'ALL'){
      return (<Col span={18}><span className='column-content'>{messages('financial-management.key432'/*全部*/)}</span></Col>)
    }else if(item.receiptedPeriodState === 'CURRENTMONTH'){
      return (<Col span={18}><span className='column-content'>{messages('financial-management.key464'/*当月*/)}</span></Col>)
    }else{
      return (<Col span={18}>
        {item.startMonth === 101 ? <span className='column-content'>{messages('financial-management.key466'/*上月*/)}</span> : <span className='column-content'>{messages('financial-management.key464'/*当月*/)}</span>}
        <span className='column-content'>{item.startDay+'日'}</span>
        <span className='column-content'>{messages('financial-management.key430'/*至*/)}</span>
        {item.endMonth === 101 ? <span className='column-content'>{messages('financial-management.key466'/*上月*/)}</span> : <span className='column-content'>{messages('financial-management.key464'/*当月*/)}</span>}
        <span className='column-content'>{item.endDay+'日'}</span>
      </Col>)
    }
  };

  //渲染支付方式
  renderPaymentType = (item) =>{
    if(Number(item.paymentType) === 1001){
      return (
        <Col span={18}><span className='column-content'>{messages('financial-management.key411'/*个人垫付*/)}</span></Col>
      )
    }else if(Number(item.paymentType) === 1002){
      return (
        <Col span={18}><span className='column-content'>{messages('financial-management.key412'/*公司垫付*/)}</span></Col>
      )
    }else{
      return (
        <Col span={18}><span className='column-content'>{messages('financial-management.key432'/*全部*/)}</span></Col>
      )
    }
  };

  //渲染商务卡支付
  renderCommercialType = (item) =>{
    let content = item.bankCardTypeEntity ? item.bankCardTypeEntity.entityName : messages('common.all');
    return (
      <Col span={18}><span className='column-content'>{content}</span></Col>
    )
  };

  renderBillingType = () => {
    const { billingType } = this.state;
    let result = '';
    switch (billingType){
      case 'DIDI':
        result = messages('financial-management.key423'/*滴滴账户*/);
        break;
      case 'CLOUD_HELIOS_HOTEL':
        result = messages('financial-management.key548'/*甄选账号*/);
        break;
      case 'SHEN_ZHOU':
        result = messages('financial-management.key549'/*神州账户*/);
        break;
      default:
        result = '';
        break;
    }
    return result;
  };

  renderRules = () => {
    const { receiptRules, billingType, total, keyInvoiceOIDArray, page } = this.state;
    return (
      <div>
        <Row>
          {
            receiptRules.map((item,index) =>(
              <Col span={8} style={{padding: '0px 5px 20px'}} key={index}>
                <Card bordered={true} style={{height: '500px', overflowY: 'auto'}}>
                  <div className='column-head'>
                    <Checkbox
                      className="f-left"
                      onChange={this.boxChange}
                      value={item.keyInvoiceOID}
                      checked={keyInvoiceOIDArray.indexOf(item.keyInvoiceOID) > -1}
                    >{item.keyInvoiceName}</Checkbox>
                    <Dropdown className="f-right" overlay={
                      <Menu onClick={(e) => this.menuHandleClick(e,item.keyInvoiceOID)} style={{padding:'0 10px',float:"right"}}>
                        <Menu.Item key="open">{messages('financial-management.key499'/*开票*/)}</Menu.Item>
                        <Menu.Item key="edit">{messages('financial-management.key500'/*编辑*/)}</Menu.Item>
                        <Menu.Item key="delete">{messages('financial-management.key501'/*删除*/)}</Menu.Item>
                      </Menu>
                    }>
                      <Icon type="ellipsis" style={{fontSize: '30px', color: '#2592FC'}}/>
                    </Dropdown>
                  </div>
                  <Row style={{marginTop:'10px'}}>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key428'/*开票抬头*/)}：</span></Col>
                    <Col span={18}><span className='column-content'>{item.title}</span></Col>
                  </Row>
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key481'/*基准日期*/)}：</span></Col>
                    <Col span={18}><span className='column-content'>{messages('financial-management.key564')/*审核日期*/}</span></Col>
                  </Row>
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key433'/*开票类型*/)}：</span></Col>
                    <Col span={18}><span className='column-content'>{item.invoiceTypeResp?item.invoiceTypeResp.name:''}</span></Col>
                  </Row>
                  {
                    billingType !== 'CLOUD_HELIOS_HOTEL' &&
                    <Row>
                      <Col span={6}><span className='column-name'>{this.renderBillingType()}：</span></Col>
                      <Col span={18}><span className='column-content'>{item.vendorAccountName}</span></Col>
                    </Row>}
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key429'/*日期范围*/)}：</span></Col>
                    {this.renderTicketPeriod(item)}
                  </Row>
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key467'/*支付方式*/)}：</span></Col>
                    {this.renderPaymentType(item)}
                  </Row>
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key434'/*单据信息法人*/)}：</span></Col>
                    {this.renderList(item,'expenseSearchLegalEntities','entityName')}
                  </Row>
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key495'/*单据部门*/)}：</span></Col>
                    {this.renderList(item,'expenseSearchDepartments','entityName')}
                  </Row>
                  <Row>
                    <Col span={6}><span className='column-name'>{messages('financial-management.key431'/*单据信息成本中心*/)}：</span></Col>
                    {this.renderList(item,'costCenters','entityName')}
                  </Row>
                  {item.bankCardType &&
                  (
                    <Row>
                      <Col span={6}><span className='column-name'>{messages('financial-management.key436'/*商务卡支付*/)}：</span></Col>
                      {this.renderCommercialType(item)}
                    </Row>
                  )
                  }
                  <Row>
                    <Col span={6}><span className='column-name'>{messages(~['ELECTRONICORDINARY'].indexOf(item.invoiceApplyType)?'financial-management.key473':'financial-management.key475')}：</span></Col>
                    {this.renderAddressDetail(item)}
                  </Row>
                </Card>
              </Col>
            ))
          }
        </Row>
        <Pagination
          pageSize={9}
          current={ page + 1 }
          onChange={this.onChangePaper}
          total={total}
          showQuickJumper
          size='small'
        />
      </div>
    )
  };

  onChangePaper = page => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getAllRules()
      })
    }
  };

  render(){
    const { loading,showSlideFrame,frameData, billingType, total, modelEnum, keyInvoiceOIDArray, excludeOids,
      title, checked, openLoading } = this.state;
    let length = 0;
    if (modelEnum === 'ALL_PAGE') {
      length = total - excludeOids.length;
    } else {
      length = keyInvoiceOIDArray.length;
    }
    return (
      <div className="new-billing">
        <div className='form-area'>
          <NewBillingForm  billingType={billingType} newBillingRule={value =>this.newBillingRule(value)} toSearchBilling={value =>this.toSearchNewBilling(value)}/>
        </div>
        <div className="divider"/>
        <div className='billing-rules'>
          <div className='top-area'>
            <div className='title'>{messages('financial-management.key502'/*常用开票条件*/)}({total ? total : ''})</div>
          </div>
          <div style={{clear: "both"}}>
            <Checkbox onChange={this.chooseAllRules} checked={checked}/>
            <Dropdown overlay={<Menu onClick={this.handleChangeType} getPopupContainer={triggerNode => triggerNode.parentNode}>
              <Menu.Item key="ALL_PAGE">{messages('financial-management.key178')/*全选全部*/}</Menu.Item>
              <Menu.Item key="CURRENT_PAGE">{messages('financial-management.key177')/*全选当页*/}</Menu.Item>
            </Menu>}>
              <span>{title === 'ALL_PAGE' ? messages('financial-management.key178')/*全选全部*/ : messages('financial-management.key177')/*全选当页*/}<Icon type="down" /></span>
            </Dropdown>
            <Button type='primary' style={{marginLeft:'20px'}} disabled={!length} onClick={this.showTicketModal}>{messages('financial-management.key504'/*批量开票*/)}({length})</Button>
            <Button type='primary' style={{marginLeft:'20px'}} disabled={!length} onClick={this.openTicket} loading={openLoading}>
              {messages('financial-management.key963')/*一键开票*/}({length})
            </Button>
          </div>
          <Spin spinning={loading}>
            <div className='billing-rules-card'>
              {total > 0 ?
                <Row gutter={30}>
                  {this.renderRules()}
                </Row>
                :
                <div className='no-billing-rules-tips'>{messages('financial-management.key505'/*无常用开票条件，请点击上方【存为常用开票条件】进行新建*/)}</div>
              }
            </div>
          </Spin>
        </div>
        <SlideFrame title={frameData.type === 'single' ? messages('financial-management.key499'/*开票*/) : messages('financial-management.key504'/*批量开票*/)}
                    show={showSlideFrame}
                    content={OpenTicketFrame}
                    onClose={() => this.showSlide(false)}
                    afterClose={this.handleCloseSlide}
                    params={{frameData,slideFrameShowFlag:showSlideFrame,billingType:billingType}}
        />
      </div>
    )
  }
}

NewBilling.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(NewBilling);
